package com.cmcc.aregister.ui.activity;

import com.appointmentregister.sina.RequestToken;
import com.cmcc.aregister.R;
import com.oauth.data.OAuth;
import com.oauth.utils.ConfigUtil;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * 用户授权页面
 * 		1.初始化OAuth对象
 * 		2.获取用户授权页面并填充至webView
 * 		3.根据载入的url判断匹配规则的结果执行跳�? * 
 * @author bywyu
 *
 */
@SuppressLint("NewApi")
public class AuthorizationAct extends ParentActivity {
//	private final String TAG = "AuthorizationAct";
	private ConfigUtil conf = ConfigUtil.getInstance();
	RequestToken requestToken = null;
	String url = null;
	private ProgressDialog progressDlg;
	WebView authorizationView;
	@Override
    protected void onCreate(Bundle savedInstanceState) {
	    // TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_PROGRESS);//让进度条显示在标题栏上   
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.authorization_ui);
	    progressDlg = new ProgressDialog(AuthorizationAct.this);
	    progressDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    progressDlg.setTitle(getString(R.string.notice));
	    progressDlg.setIcon(android.R.drawable.ic_dialog_info);
	    progressDlg.setMessage(getString(R.string.loading_web));
	    progressDlg.setCancelable(true);
	    progressDlg.show();
	    
		new Thread(){
			public void run(){
				try {
					OAuth  oAuth = OAuth.getInstance();
				    oAuth.clear();
				    String appKey = conf.getAppKey();
				    String appSecret = conf.getAppSecret();
				    oAuth.setKeyAndSecret(appKey, appSecret);
				    url = oAuth.getAuthorizUrl();
					initWebView(url);
				} catch (Exception e) {
					progressDlg.dismiss();
				}
			}
		}.start(); 
    }
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
	}
	private void initWebView(String url) {
		authorizationView = (WebView) findViewById(R.id.authorizationView);
	    authorizationView.clearCache(true);
	    authorizationView.getSettings().setJavaScriptEnabled(true);
	    authorizationView.getSettings().setSupportZoom(true);
	    authorizationView.getSettings().setBuiltInZoomControls(true);
	    authorizationView.setWebViewClient(new WebViewC()); 
	    /*authorizationView.setWebChromeClient(new WebChromeClient() {  
	    	public void onProgressChanged(WebView view, int progress) {  
	    		//Activity和Webview根据加载程度决定进度条的进度大小   
	    		//当加载到100%的时候 进度条自动消失   
	    		setProgress(progress * 100);  
	    	}  
	    	 //设置网页加载的进度条   
	        public void onProgressChanged(WebView view,int newProgress){   
	            AuthorizationAct.this.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress*100);   
	            super.onProgressChanged(view, newProgress);   
	        }
	    }); */
	    authorizationView.loadUrl(url);
    }
	@Override  
	public boolean onKeyDown(int keyCode, KeyEvent event) {   
		if(keyCode==KeyEvent.KEYCODE_BACK && authorizationView != null && authorizationView.canGoBack()){   
			authorizationView.goBack();//返回前一个页面   
			return true;   
		}   
		return super.onKeyDown(keyCode, event);   
	}   
	class WebViewC extends WebViewClient{
		private int index = 0;
		@Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
        }
		
		/**
		 * 由于腾讯授权页面采用https协议
		 * 		执行此方法接受所有证�?		 */
		public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
			 handler.proceed();
			 progressDlg.dismiss();
		 }

		@Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);

			/**
			 *  url.contains(ConfigUtil.callBackUrl)
			 *  如果授权成功url中包含之前设置的callbackurl
			 *  		包含：授权成�?	         *
			 *index == 0
			 *由于该方法onPageStarted可能被多次调用�?成重复跳�?	         *		则添加此标示
			 */

			if( url.contains(ConfigUtil.callBackUrl) && index == 0){
				index ++;
				Intent intent = new Intent(AuthorizationAct.this,ShareActivity_qq.class);
				intent.putExtra(ConfigUtil.OAUTH_VERIFIER_URL, url);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				AuthorizationAct.this.startActivity(intent);
				AuthorizationAct.this.finish();
			}
        }
 
		@Override
        public void onPageFinished(WebView view, String url) {
	        // TODO Auto-generated method stub
	        super.onPageFinished(view, url);
//	        view.loadUrl("javascript:window.Methods.getHTML('<head>'+document.getElementsByTagName('body')[0].innerHTML+'</head>');");
	        progressDlg.dismiss();
        }
	}
}
